/**
 * 
 */
package com.axxc.cloud.es.index.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.axxc.cloud.es.index.document.ArticleDemo;
import com.axxc.cloud.es.index.filter.ArticleDemoFilter;
import com.axxc.cloud.es.index.repository.IArticleDemoRepository;
import com.axxc.cloud.vo.ResponseVO;
import com.github.pagehelper.util.StringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @ClassName: ArticleDemoController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author 熊小川
 * @date 2018年6月3日 上午12:25:13
 * @See
 */
@RequestMapping("/articledemo")
@RestController
@Api(description = "articledemo接口文档")
public class ArticleDemoController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private IArticleDemoRepository articleDemoRepository;

	@PostMapping("/addArtcileDemo")
	@ApiOperation(value = "新增文章", notes = "新增文章")
	public void buildIndexAndMapper() {
		List<ArticleDemo> arrayList = new ArrayList<ArticleDemo>();
		ArticleDemo article;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy:mm:dd hh:MM:ss");
		for (int i = 0; i < 300; i++) {
			article = new ArticleDemo();
			article.setAuthor(i + "熊骑士");
			article.setContent(i + "今天基于springboot整合sping-data-elasticserach,学习ES搜索引擎技术及IK分词查询API语法,并简单测试其CRUD API");
			article.setCreateTime(simpleDateFormat.format(new Date()));
			article.setId(i);
			article.setTitle(i + "springboot整合sping-data-elasticserach");
			arrayList.add(article);
		}
		this.articleDemoRepository.save(arrayList);
	}

	@PostMapping("/search")
	@ApiOperation(value = "搜索文章", notes = "搜索文章")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "page", value = "当前页,此参数从0开始", paramType = "query"),
			@ApiImplicitParam(name = "size", value = "每页显示数量,此参数默认20", paramType = "query") })
	public ResponseVO search(@ModelAttribute ArticleDemoFilter filter, String page, String size) {
		logger.info("" + JSONObject.toJSON(filter));
		ResponseVO responseVO = new ResponseVO();
		page = StringUtils.isBlank(page) == true || Integer.valueOf(page) < 0 ? "0" : page;
		size = StringUtils.isBlank(size) == true || Integer.valueOf(size) < 0 ? "20" : size;
		Pageable pageable = new PageRequest(Integer.valueOf(page), Integer.valueOf(size));
		if (StringUtil.isEmpty(String.valueOf(filter.getId())) && StringUtil.isEmpty(filter.getTitle())
				&& StringUtil.isEmpty(filter.getContent()) && StringUtil.isEmpty(filter.getAuthor())) {
			Page<ArticleDemo> pageData = this.articleDemoRepository.findAll(pageable);
			responseVO.setTotal(pageData.getTotalElements());
			responseVO.setContent(pageData.getContent());
		} else {
			// Criteria criteria = new Criteria();

			BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
			if (filter.getId() != null && filter.getId() >= 0) {
				TermQueryBuilder termQueryBuilder = new TermQueryBuilder("id", filter.getId());
				boolQueryBuilder.must(termQueryBuilder);
			}
			if (!StringUtil.isEmpty(filter.getAuthor())) {
				WildcardQueryBuilder termQueryBuilder = new WildcardQueryBuilder("author",
						"*" + filter.getAuthor() + "*");
				boolQueryBuilder.must(termQueryBuilder);
			}
			if (!StringUtil.isEmpty(filter.getTitle())) {
				// 单词条模糊匹配查询
				WildcardQueryBuilder termQB = new WildcardQueryBuilder("title", "*" + filter.getTitle() + "*");
				// No.2多词条时分词匹配 AND
				QueryStringQueryBuilder stringQueryBuilder = new QueryStringQueryBuilder(filter.getTitle())
						.field("title").defaultOperator(Operator.AND);
				// 两种情况 OR
				BoolQueryBuilder tempBoolQueryBuilder = new BoolQueryBuilder();
				tempBoolQueryBuilder.should(termQB);
				tempBoolQueryBuilder.should(stringQueryBuilder);
				boolQueryBuilder.must(tempBoolQueryBuilder);

			}
			if (!StringUtil.isEmpty(filter.getContent())) {
				// No.1 单词条匹配
				WildcardQueryBuilder termQueryBuilder = new WildcardQueryBuilder("content",
						"*" + filter.getContent() + "*");
				// No.2多词条时分词匹配 AND
				QueryStringQueryBuilder stringQueryBuilder = new QueryStringQueryBuilder(filter.getContent())
						.field("content").defaultOperator(Operator.AND);
				// 两种情况 OR
				BoolQueryBuilder tempBoolQueryBuilder = new BoolQueryBuilder();
				tempBoolQueryBuilder.should(termQueryBuilder);
				tempBoolQueryBuilder.should(stringQueryBuilder);
				boolQueryBuilder.must(tempBoolQueryBuilder);
			}
			// logger.info("" + JSONObject.toJSON(boolQueryBuilder));
			SearchQuery searchQuery = new NativeSearchQuery(boolQueryBuilder);
			searchQuery.setPageable(pageable);

			Page<ArticleDemo> pageData = this.articleDemoRepository.search(searchQuery);
			responseVO.setTotal(pageData.getTotalElements());
			responseVO.setContent(pageData.getContent());
		}

		return responseVO;

	}

}
